/*
 *  Copyright (c) 2006-2007 Tiark Rompf, Nachtlicht-Media
 *  
 *  All rights reserved. This software is copyrighted work licensed under
 *  the terms of the MIT License.  Please consult the file "LICENSE" for
 *  details. There is NO warranty.
 *  
 *  $Id:$
 */

import java.util.concurrent.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.media.opengl.*;
import javax.media.opengl.glu.*;
import com.sun.opengl.util.*;
//import com.sun.opengl.util.Texture.*;

public class STGLCanvas extends Canvas
{
    private GLDrawable drawable;
    private GLContext context;
    private boolean ok = false;

    public STGLCanvas()
    {
        this(null);
    }

    public STGLCanvas(GLCapabilities capabilities)
    {
        this(capabilities, null, null, null);
    }

    public STGLCanvas(GLCapabilities capabilities, GLCapabilitiesChooser chooser, GLContext shareWith, GraphicsDevice device)
    {
        super(unwrap((AWTGraphicsConfiguration)GLDrawableFactory.getFactory().chooseGraphicsConfiguration(capabilities, chooser, new AWTGraphicsDevice(device))));
        drawable = GLDrawableFactory.getFactory().getGLDrawable(this, capabilities, chooser);
        context = drawable.createContext(shareWith);
    }

    public void addNotify()
    {
        super.addNotify();
        drawable.setRealized(true);
        ok = true;
    }

    public void update(Graphics g)
    {
    }

    public void paint(Graphics g)
    {
    }


	
	public boolean isAvailable()
	{
		return ok;
	}
	
	public GLContext getContext()
	{
		return context;
	}

	public GLDrawable getDrawable()
	{
		return drawable;
	}
	
	
	
	static final float SIZE = 0.3f;
	static int angle = 0;
	
	public void renderInit()
	{
        final GL gl = context.getGL();
        final GLU glu = new GLU();


		gl.glMatrixMode(GL.GL_PROJECTION);
		gl.glLoadIdentity();
		glu.gluOrtho2D(-1.0f, 1.0f, -1.0f, 1.0f); // drawing square
		gl.glMatrixMode(GL.GL_MODELVIEW);
		gl.glLoadIdentity();

		gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f); //erasing color
		gl.glColor3f(0.0f, 0.0f, 0.0f); // drawing color
	}
	
	public void renderFrame()
	{
        final GL gl = context.getGL();
        
		 // normal opengl rendering goes here

		gl.glClear(GL.GL_COLOR_BUFFER_BIT);

		gl.glColor3f(1, 0, 0);
		gl.glRectf(-SIZE / 2, -SIZE / 2, SIZE / 2, SIZE / 2);
		gl.glColor3f(0.0f, 0.0f, 0.0f);
		
		angle++;
		
		gl.glMatrixMode(GL.GL_MODELVIEW);
		gl.glLoadIdentity();
		gl.glRotatef(angle, 0, 0, 1);


		drawable.swapBuffers();
	}

	public void renderExit()
	{
		context.release();
		context.destroy();
	}
	
	
	

// {
//        context.release();
//        context.destroy();
//       System.exit(0);
//  }


    private static GraphicsConfiguration unwrap(AWTGraphicsConfiguration config)
    {
        if (config == null) { return null; }
        return config.getGraphicsConfiguration();
    }
}